import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutterdemo/utils/date_util.dart';

class NotificationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _NotificationPageState();
  }
}

class _NotificationPageState extends State<NotificationPage> {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('通知栏'),
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            OutlineButton(
              child: Text('显示通知'),
              onPressed: () {
                _show();
              },
            ),
            OutlineButton(
              child: Text('调度的通知'),
              onPressed: () {
                _showSchedule();
              },
            ),
          ],
        ),
        OutlineButton(
          child: Text('周期性地示出具有指定的时间间隔的通知'),
          onPressed: () {
            _showEvery();
          },
        ),
        OutlineButton(
          child: Text('在特定时间显示每日通知'),
          onPressed: () {
            _showTimer();
          },
        ),
        OutlineButton(
          child: Text('显示在特定日期和时间每周通知'),
          onPressed: () {
            _showWeekTime();
          },
        ),
        RaisedButton(
          elevation: 15,
          child: Text('挂起通知请求'),
          onPressed: () {
            _suspend();
          },
        ),
        FlatButton(
            child: Text('清除所有'),
            onPressed: () {
              _cancelAll();
            }),
      ],
    );
  }

  _init() async {
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    var initializationSettingsAndroid;
    if (Platform.isAndroid) {
      initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    }
    var initializationSettingsIOS;
    if (Platform.isIOS) {
      //然后requestPermissions在应用程序的适当位置以所需的权限调用该方法
      initializationSettingsIOS = IOSInitializationSettings(
        requestSoundPermission: false,
        requestBadgePermission: false,
        requestAlertPermission: false,
        onDidReceiveLocalNotification: onDidReceiveLocalNotification,
      );
    }
    var initializationSettingsMacOS;
    if (Platform.isMacOS) {
      initializationSettingsMacOS = MacOSInitializationSettings();
    }
    var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
      macOS: initializationSettingsMacOS,
    );
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: selectNotification);
  }

  ///选择通知栏
  Future selectNotification(String payload) async {
    if (payload != null) {
      print('选择通知栏notification payload: ' + payload);
    }
//    await Navigator.push(
//      context,
//      MaterialPageRoute(builder: (context) => SecondScreen(payload)),
//    );
  }

  Future onDidReceiveLocalNotification(
      int id, String title, String body, String payload) async {
    // display a dialog with the notification details, tap ok to go to another page
    showDialog(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
        title: Text(title),
        content: Text(body),
        actions: [
          CupertinoDialogAction(
            isDefaultAction: true,
            child: Text('Ok'),
            onPressed: () async {
              Navigator.of(context, rootNavigator: true).pop();
//              await Navigator.push(
//                context,
//                MaterialPageRoute(
//                  builder: (context) => SecondScreen(payload),
//                ),
//              );
            },
          )
        ],
      ),
    );
  }

  _show() async {
    var scheduledNotificationDateTime =
        DateTime.now().add(Duration(seconds: 5));
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.max, priority: Priority.high, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var macOsPlatformChannelSpecifics = MacOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
      macOS: macOsPlatformChannelSpecifics,
    );
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        0, 'plain title标题', 'plain body通知栏内容', platformChannelSpecifics,
        payload: 'item payload');
//    await flutterLocalNotificationsPlugin.schedule(
//        0,
//        'scheduled title',
//        'scheduled body',
//        scheduledNotificationDateTime,
//        platformChannelSpecifics);
  }

  _cancelAll() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }

  ///调度的通知
  _showSchedule() async {
    var scheduledNotificationDateTime =
        DateTime.now().add(Duration(seconds: 5));
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your other channel id',
        'your other channel name',
        'your other channel description');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var macOsPlatformChannelSpecifics = MacOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
      macOS: macOsPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.schedule(
        0,
        'scheduled title',
        'scheduled body',
        scheduledNotificationDateTime,
        platformChannelSpecifics);
  }

  ///周期性地示出具有指定的时间间隔的通知
  _showEvery() async {
    // Show a notification every minute with the first appearance happening a minute after invoking the method
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'repeating channel id',
        'repeating channel name',
        'repeating description');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var macOsPlatformChannelSpecifics = MacOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
      macOS: macOsPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title',
        'repeating body', RepeatInterval.everyMinute, platformChannelSpecifics);
  }

  ///在特定时间显示每日通知
  _showTimer() async {
    var time = Time(10, 0, 0);
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'repeatDailyAtTime channel id',
        'repeatDailyAtTime channel name',
        'repeatDailyAtTime description');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var macOsPlatformChannelSpecifics = MacOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
      macOS: macOsPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.showDailyAtTime(
        0,
        'show daily title',
        'Daily notification shown at approximately ${DateUtil.digits(time.hour, 2)}'
            ':${DateUtil.digits(time.minute, 2)}:${DateUtil.digits(time.second, 2)}',
        time,
        platformChannelSpecifics);
  }

  ///显示在特定日期和时间每周通知
  _showWeekTime() async {
    var time = Time(10, 0, 0);
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'show weekly channel id',
        'show weekly channel name',
        'show weekly description');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var macOsPlatformChannelSpecifics = MacOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
      macOS: macOsPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
        0,
        'show weekly title',
        'Weekly notification shown on Monday at approximately ${DateUtil.digits(time.hour, 2)}'
            ':${DateUtil.digits(time.minute, 2)}:${DateUtil.digits(time.second, 2)}',
        Day.monday,
        time,
        platformChannelSpecifics);
  }

  ///挂起通知请求
  _suspend() async {
    var pendingNotificationRequests =
        await flutterLocalNotificationsPlugin.pendingNotificationRequests();
  }
}
